# -*- coding: utf-8 -*-
from functools import partial

from sqlalchemy.exc import IntegrityError

from common.lottery.cyclical.abstract import activity as base
from common.utils.decorator import sql_wrapper
from common.lottery import LOTTERY_TYPE


fullfill_result = sql_wrapper(
    partial(base.fullfill_result, LOTTERY_TYPE.FF_PK10))


get_latest_term = sql_wrapper(
    partial(base.get_latest_term, LOTTERY_TYPE.FF_PK10))


get_activity_by_term = sql_wrapper(
    partial(base.get_activity_by_term, LOTTERY_TYPE.FF_PK10))


stop_term = sql_wrapper(
    partial(base.stop_term, LOTTERY_TYPE.FF_PK10))


create_new_term = sql_wrapper(
    partial(base.create_new_term, LOTTERY_TYPE.FF_PK10))


get_stats_by_term = sql_wrapper(
    partial(base.get_stats_by_term, LOTTERY_TYPE.FF_PK10))


get_activity_stats = sql_wrapper(
    partial(base.get_activity_stats, LOTTERY_TYPE.FF_PK10))


def calc_miss(last_stats, number, save, trend):
    def calc_func(last, i):
        return str(int(last[i]) + 1) if last[i] != 'x' else 'x'
    numbers = number.split(',')
    # 大小单双
    config = {
        'miss_7': 0,
        'miss_8': 1,
        'miss_9': 2
    }
    for k, v in config.iteritems():
        incr = ['0'] * 4
        last = getattr(last_stats, k).split(',')
        target = int(numbers[v])
        if target >= 6:  # 大
            incr[1] = calc_func(last, 1)
        else:
            incr[0] = calc_func(last, 0)
        if int(target) % 2 == 0:
            incr[2] = calc_func(last, 2)
        else:
            incr[3] = calc_func(last, 3)

        if 'x' in incr:
            save = False

        setattr(trend, k, ','.join(incr))

    incr = ['0'] * 2
    last = last_stats.miss_10.split(',')
    if int(numbers[0]) > int(numbers[-1]):  # 龙
        incr[1] = calc_func(last, 1)
    else:
        incr[0] = calc_func(last, 0)
    if 'x' in incr:
        save = False
    trend.miss_10 = ','.join(incr)
    return trend, save


@sql_wrapper
def insert_stats(term, number, last_stats):
    trend, save = base.generate_trend(
        LOTTERY_TYPE.FF_PK10, term, number, last_stats)

    trend, save = calc_miss(last_stats, number, save, trend)

    if save:
        try:
            trend.save()
        except IntegrityError:
            pass
    return trend
